﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace PongRemix.ui
{

    ///<summary>
    /// Student List:
    ///         RJ Hill            rhill3@my.westga.edu
    ///         Shapna Kumar       kumar.shapna@gmail.com
    ///         Guillem Martinez   gmartin2@my.westga.edu>
    ///         Rodolfo Vasquez    xra_vasquezx@yahoo.com>
    ///         Mike Kemakolam"    mkemako1@my.westga.edu>
    ///</summary>
    class CollisionChecker : GameComponent
    {
        private List<Sprite> collisionSubjects;
        private List<BoundingBox> collisionDeterminers;

        public CollisionChecker(Game game)
            : base(game)
        {
            collisionSubjects = new List<Sprite>();
            collisionDeterminers = new List<BoundingBox>();
        }

        public void AddCollisionSprite(Sprite subject)
        {
            collisionSubjects.Add(subject);
            collisionDeterminers.Add(new BoundingBox());
            //collisionDeterminers.Add(new BoundingBox(new Vector3(subject.GetPosition(), 0), new Vector3(subject.GetPosition().X + subject.GetTexture().Width, subject.GetPosition().Y + subject.GetTexture().Height, 0)));
        }

        public bool CheckCollision(Sprite subject)
        {
            int subjectIndex = collisionSubjects.IndexOf(subject);
            collisionDeterminers[subjectIndex] = new BoundingBox(new Vector3(subject.GetPosition(), 0),
                new Vector3(subject.GetPosition().X + subject.GetTexture().Width, subject.GetPosition().Y + subject.GetTexture().Height, 0));
            int currentIndex = 0;

            foreach (BoundingBox otherBox in collisionDeterminers)
            {
                if (currentIndex != subjectIndex)
                {
                    if (collisionDeterminers[subjectIndex].Intersects(collisionDeterminers[currentIndex])) { return true; }
                }
                currentIndex++;
            }

            return false;
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            foreach (Sprite subject in collisionSubjects)
            {
                if (CheckCollision(subject))
                {
                    if (subject.GetVelocity().X > 200f)
                    {
                        subject.SetVelocity(new Vector2((-subject.GetVelocity().X), subject.GetVelocity().Y));
                    }
                    else
                    {
                        subject.SetVelocity(new Vector2((-subject.GetVelocity().X * 1.25f), subject.GetVelocity().Y));
                    }
                }
            }
        }
    }
}
